package 面向对象.实验10;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author IT_Jay
 * @date 2021/12/16 12:41 PM
 */
public class Server03 extends Thread{
    ServerSocket server = null;
    Socket socket = null;
    static int count = 0;
    static List<Socket> list = new ArrayList<>();
    public Server03(int port) {

        try {
            server = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run(){

        super.run();
        try{
            System.out.println("Three===========wait client connect...");
            socket = server.accept();
//            new sendMessThread().start();//连接并返回socket后，再启用发送消息线程
            System.out.println(socket.getInetAddress().getHostAddress()+"SUCCESS TO CONNECT...");
            synchronized (this) {
                count++;
                list.add(socket);
            }
            InputStream in = socket.getInputStream();
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len=in.read(buf))!=-1){
                String s = new String(buf, 0, len);
                System.out.println("该用户上线线了: "+s+" 当前有:"+list.size());
                for (Socket socket1 : list) {
                    OutputStream out = socket1.getOutputStream();
                    out.write(("该用户上线线了: "+s).getBytes());
                    out.flush();
                }
            }

        }catch (IOException e){
            e.printStackTrace();
        }
    }




    //函数入口
    public static void main(String[] args) {
        Server03 server = new Server03(1234);
        Server03 server1 = new Server03(1235);
        server.start();
        server1.start();
    }
}

